package com.acaslless.core.utils;

import cn.hutool.core.net.NetUtil;
import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
import com.acaslless.core.constant.Constant;
import com.acaslless.core.enums.ResultEnum;
import com.acaslless.core.exception.ServiceException;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet 工具
 *
 * @author haohan
 * @date 2024/9/12 16:23
 **/
public class ServletUtil {

    /**
     * 获取 request
     * */
    public static HttpServletRequest getRequest() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes == null) {
            throw new ServiceException(ResultEnum.FAIL);
        } else {
            return attributes.getRequest();
        }
    }

    /**
     * 获取response
     * */
    public static HttpServletResponse getResponse() {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        if (servletRequestAttributes == null) {
            throw new ServiceException(ResultEnum.FAIL);
        } else {
            return servletRequestAttributes.getResponse();
        }
    }

    /**
     * 查询用户id
     * */
    public static Long getUserId() {
        return Long.valueOf(getRequest().getHeader(Constant.HTTP_USER_ID));
    }

    /**
     * 查询用户名称
     * */
    public static String getAccount() {
        return getRequest().getHeader(Constant.HTTP_USER_NAME);
    }

    /**
     * 获取ip
     * */
    public static String getIp() {
        String ip;
        String[] headers = {"X-Forwarded-For", "X-Real-IP", "Proxy-Client-IP", "WL-Proxy-Client-IP", "HTTP_CLIENT_IP", "HTTP_X_FORWARDED_FOR"};
        for (String header : headers) {
            ip = getRequest().getHeader(header);
            if (!NetUtil.isUnknown(ip)) {
                return NetUtil.getMultistageReverseProxyIp(ip);
            }
        }
        ip = getRequest().getRemoteAddr();
        return NetUtil.getMultistageReverseProxyIp(ip);
    }

    /**
     * 获取浏览器信息
     * */
    public static String getBrowser() {
        return getUserAgent().getBrowser().getName();
    }

    /**
     * 获取操作系统
     * */
    public static String getOs() {
        return getUserAgent().getOs().getName();
    }

    private static UserAgent getUserAgent() {
        HttpServletRequest request = getRequest();
        return UserAgentUtil.parse(request.getHeader(Constant.HTTP_HEADER_USER_AGENT));
    }
}
